package com.tledu.web04.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tledu.web04.model.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author cyrus
 */
@WebServlet(urlPatterns = "/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //浏览器，在发送请求的时候就会携带cookie
//        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");

        // 增加一个校验，如果登录继续进行，没有登录，定向到登录界面
        // 判断是否登录
//        HttpSession session = req.getSession();
//        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
//        if (isLogin == null || !isLogin) {
//            // 进行重定向
//            resp.sendRedirect(req.getContextPath() + "/login.jsp");
//            return;
//        }


        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        req.getRequestDispatcher("/WEB-INF/view/student.jsp").forward(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        HashMap<String, Student> studentData = (HashMap<String, Student>) this.getServletContext().getAttribute("studentData");
        studentData.remove(username);
        // 返回给界面一个json
        resp.setContentType("application/json;charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("success", true);
        resp.getWriter().println(res.toJSONString());
    }
}
